<template>
  <div class="order-page">
    <!-- 搜索和筛选区域 -->
    <div class="search-filter-section">
      <el-card>
        <div class="filter-container">
          <!-- 返回按钮放在最左侧 -->
          <el-button @click="handleBackToGoods">
            <el-icon><ArrowLeft /></el-icon>
            返回商品页
          </el-button>

          <el-input
            v-model="searchKeyword"
            placeholder="搜索订单ID、商品名称、对方昵称"
            style="width: 300px"
            clearable
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
            <template #append>
              <el-button @click="handleSearch">
                <el-icon><Search /></el-icon>
              </el-button>
            </template>
          </el-input>
          
          <el-select
            v-model="filterForm.role"
            placeholder="订单角色"
            style="width: 150px"
            @change="handleFilter"
          >
            <el-option label="我购买的" value="buyer" />
            <el-option label="我出售的" value="seller" />
          </el-select>

          <el-select
            v-model="filterForm.status"
            placeholder="订单状态"
            style="width: 150px"
            clearable
            @change="handleFilter"
          >
            <el-option label="待处理" :value="1" />
            <el-option label="进行中" :value="2" />
            <el-option label="已完成" :value="3" />
            <el-option label="已取消" :value="0" />
          </el-select>

          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>

          <!-- 管理我的商品按钮 -->
          <el-button type="success" @click="handleManageMyGoods">
            <el-icon><Goods /></el-icon>
            管理我的商品
          </el-button>
        </div>
      </el-card>
    </div>

    <!-- 订单列表 -->
    <div class="orders-list-section">
      <el-row v-loading="loading" :gutter="16">
        <el-col
          v-for="order in orders"
          :key="order.order_id"
          :xs="24"
          :sm="12"
          :md="8"
          style="margin-bottom: 16px"
        >
          <el-card
            class="order-card"
            :body-style="{ padding: '0' }"
            shadow="hover"
          >
            <div style="padding: 16px">
              <!-- 订单头部信息 -->
              <div class="order-header">
                <div class="order-id">订单号: #{{ order.order_id }}</div>
                <div class="order-actions">
                  <el-tooltip content="查看详情" placement="top">
                    <el-button
                      size="small"
                      text
                      @click.stop="handleViewDetail(order)"
                    >
                      <el-icon><View /></el-icon>
                    </el-button>
                  </el-tooltip>
                  <el-tooltip 
                    v-if="canUpdateOrder(order)" 
                    content="更新状态" 
                    placement="top"
                  >
                    <el-button
                      size="small"
                      text
                      @click.stop="handleUpdateStatus(order)"
                    >
                      <el-icon><Edit /></el-icon>
                    </el-button>
                  </el-tooltip>
                  <el-tooltip 
                    v-if="canDeleteOrder(order)" 
                    content="删除订单" 
                    placement="top"
                  >
                    <el-button
                      size="small"
                      text
                      @click.stop="handleDeleteOrder(order)"
                    >
                      <el-icon><Delete /></el-icon>
                    </el-button>
                  </el-tooltip>
                </div>
              </div>

              <!-- 商品信息 -->
              <div class="goods-info" @click="handleViewGoodDetail(order.good)">
                <div class="goods-image">
                  <img 
                    v-if="getGoodImage(order.good)" 
                    :src="getGoodImage(order.good)" 
                    :alt="order.good?.title"
                    class="goods-img"
                    @error="handleImageError"
                  />
                  <div v-else class="no-goods-image">
                    <el-icon><Picture /></el-icon>
                  </div>
                </div>
                <div class="goods-details">
                  <h4 class="goods-title">{{ order.good?.title || '商品已删除' }}</h4>
                  <p class="goods-description">
                    {{ truncateDescription(order.good?.description) }}
                  </p>
                  <div class="goods-price">¥{{ order.amount }}</div>
                </div>
              </div>

              <!-- 用户信息 -->
              <div class="users-info">
                <div class="user-item">
                  <span class="user-label">{{ filterForm.role === 'buyer' ? '卖家' : '买家' }}:</span>
                  <div class="user-detail">
                    <el-avatar 
                      :src="getFullImageUrl(filterForm.role === 'buyer' ? order.seller?.avatar : order.buyer?.avatar)" 
                      :size="24" 
                    />
                    <span style="margin-left: 8px">
                      {{ (filterForm.role === 'buyer' ? order.seller?.nickname : order.buyer?.nickname) || '未知用户' }}
                    </span>
                  </div>
                </div>
              </div>

              <!-- 订单状态和时间 -->
              <div class="order-footer">
                <div class="order-status">
                  <el-tag :type="getOrderStatusType(order.status)" size="small">
                    {{ getOrderStatusText(order.status) }}
                  </el-tag>
                </div>
                <div class="order-time">
                  {{ formatTime(order.created_at) }}
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 空状态 -->
      <div v-if="orders.length === 0 && !loading" class="empty-state">
        <el-empty :description="emptyDescription" />
      </div>

      <!-- 分页 -->
      <div v-if="orders.length > 0" class="pagination-section">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[6, 12, 18, 24]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 订单详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      :title="`订单详情 - #${currentOrder?.order_id}`"
      width="600px"
    >
      <div v-if="currentOrder" class="order-detail">
        <!-- 订单基本信息 -->
        <el-descriptions title="订单信息" :column="2" border>
          <el-descriptions-item label="订单号">
            {{ currentOrder.order_id }}
          </el-descriptions-item>
          <el-descriptions-item label="订单金额">
            <span class="price">¥{{ currentOrder.amount }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag :type="getOrderStatusType(currentOrder.status)">
              {{ getOrderStatusText(currentOrder.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ formatTime(currentOrder.created_at) }}
          </el-descriptions-item>
          <el-descriptions-item label="更新时间">
            {{ formatTime(currentOrder.updated_at) }}
          </el-descriptions-item>
        </el-descriptions>

        <!-- 商品信息 -->
        <el-descriptions title="商品信息" :column="1" border style="margin-top: 20px;">
          <el-descriptions-item label="商品名称">
            {{ currentOrder.good?.title || '商品已删除' }}
          </el-descriptions-item>
          <el-descriptions-item label="商品描述">
            {{ currentOrder.good?.description || '无描述' }}
          </el-descriptions-item>
          <el-descriptions-item label="商品图片">
            <div class="goods-images">
              <img 
                v-for="(image, index) in getGoodImages(currentOrder.good)" 
                :key="index"
                :src="image" 
                :alt="currentOrder.good?.title"
                class="detail-goods-img"
                @error="handleImageError"
              />
            </div>
          </el-descriptions-item>
        </el-descriptions>

        <!-- 用户信息 -->
        <el-descriptions title="用户信息" :column="2" border style="margin-top: 20px;">
          <el-descriptions-item label="买家">
            <div class="user-info">
              <el-avatar :src="getFullImageUrl(currentOrder.buyer?.avatar)" :size="32" />
              <span style="margin-left: 8px">{{ currentOrder.buyer?.nickname }}</span>
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="卖家">
            <div class="user-info">
              <el-avatar :src="getFullImageUrl(currentOrder.seller?.avatar)" :size="32" />
              <span style="margin-left: 8px">{{ currentOrder.seller?.nickname }}</span>
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="买家电话">
            {{ currentOrder.buyer?.phone || '未填写' }}
          </el-descriptions-item>
          <el-descriptions-item label="卖家电话">
            {{ currentOrder.seller?.phone || '未填写' }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 更新状态对话框 -->
    <el-dialog
      v-model="statusDialogVisible"
      title="更新订单状态"
      width="400px"
    >
      <div v-if="currentOrder" class="status-update">
        <el-form :model="statusForm" label-width="80px">
          <el-form-item label="当前状态">
            <el-tag :type="getOrderStatusType(currentOrder.status)">
              {{ getOrderStatusText(currentOrder.status) }}
            </el-tag>
          </el-form-item>
          <el-form-item label="新状态">
            <el-select v-model="statusForm.newStatus" placeholder="请选择新状态">
              <el-option 
                v-for="status in getAvailableStatuses(currentOrder)" 
                :key="status.value"
                :label="status.label" 
                :value="status.value" 
              />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="statusDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="statusLoading" @click="handleConfirmStatusUpdate">
          确认更新
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  Search,
  View,
  Edit,
  Delete,
  Refresh,
  ArrowLeft,
  Goods,
  Picture
} from '@element-plus/icons-vue';
import { orderApi } from '@/api/order';
import { useUserStore } from '@/stores/user';

const router = useRouter();
const userStore = useUserStore();

// 响应式数据
const loading = ref(false);
const orders = ref([]);
const searchKeyword = ref('');
const detailDialogVisible = ref(false);
const statusDialogVisible = ref(false);
const statusLoading = ref(false);
const currentOrder = ref(null);

// 筛选表单
const filterForm = reactive({
  role: 'buyer', // buyer: 我购买的, seller: 我出售的
  status: ''
});

// 状态表单
const statusForm = reactive({
  newStatus: ''
});

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 6,
  total: 0
});

// 计算空状态描述
const emptyDescription = computed(() => {
  if (filterForm.role === 'buyer') {
    return filterForm.status ? `暂无${getOrderStatusText(filterForm.status)}的购买订单` : '暂无购买订单';
  } else {
    return filterForm.status ? `暂无${getOrderStatusText(filterForm.status)}的出售订单` : '暂无出售订单';
  }
});

// 获取完整的图片URL
const getFullImageUrl = (url) => {
  if (!url) return '';
  if (url.startsWith('http') || url.startsWith('//') || url.startsWith('blob:')) {
    return url;
  }
  const baseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:7001';
  if (url.startsWith('/public/')) {
    return `${baseUrl}${url}`;
  }
  return url.startsWith('/') ? `${baseUrl}${url}` : `${baseUrl}/${url}`;
};

// 处理图片加载错误
const handleImageError = (event) => {
  console.error('图片加载失败:', event.target.src);
  event.target.src = '';
};

// 获取商品图片
const getGoodImage = (good) => {
  if (!good || !good.images) return '';
  let imageUrl = '';
  if (Array.isArray(good.images)) {
    imageUrl = good.images[0] || '';
  } else if (typeof good.images === 'string') {
    if (good.images.includes(',')) {
      imageUrl = good.images.split(',')[0] || '';
    } else {
      imageUrl = good.images;
    }
  }
  return getFullImageUrl(imageUrl);
};

// 获取商品所有图片
const getGoodImages = (good) => {
  if (!good || !good.images) return [];
  let imageUrls = [];
  if (Array.isArray(good.images)) {
    imageUrls = good.images.filter(url => url && url.trim());
  } else if (typeof good.images === 'string') {
    if (good.images.includes(',')) {
      imageUrls = good.images.split(',').filter(url => url && url.trim());
    } else if (good.images.trim()) {
      imageUrls = [good.images.trim()];
    }
  }
  const fullUrls = imageUrls.map(url => getFullImageUrl(url));
  return fullUrls;
};

// 截断描述文本
const truncateDescription = (description) => {
  if (!description) return '';
  const desc = String(description);
  return desc.length > 30 ? desc.substring(0, 30) + '...' : desc;
};

// 订单状态类型映射
const getOrderStatusType = (status) => {
  const types = {
    0: 'info',      // 已取消
    1: 'warning',   // 待处理
    2: 'primary',   // 进行中
    3: 'success'    // 已完成
  };
  return types[status] || '';
};

// 订单状态文本映射
const getOrderStatusText = (status) => {
  const texts = {
    0: '已取消',
    1: '待处理',
    2: '进行中',
    3: '已完成'
  };
  return texts[status] || '未知状态';
};

// 格式化时间
const formatTime = (time) => {
  if (!time) return '';
  return new Date(time).toLocaleString();
};

// 检查是否可以更新订单
const canUpdateOrder = (order) => {
  // 只有卖家可以更新订单状态，且订单不是已完成或已取消状态
  return order.seller_id === userStore.userInfo?.user_id && 
         order.status !== 0 && 
         order.status !== 3;
};

// 检查是否可以删除订单
const canDeleteOrder = (order) => {
  // 只有买家和卖家可以删除已取消或已完成的订单
  const userId = userStore.userInfo?.user_id;
  return (order.buyer_id === userId || order.seller_id === userId) && 
         (order.status === 0 || order.status === 3);
};

// 获取可用的状态选项
const getAvailableStatuses = (order) => {
  const currentStatus = order.status;
  const options = [];
  
  if (currentStatus === 1) { // 待处理
    options.push({ label: '进行中', value: 2 });
    options.push({ label: '已完成', value: 3 });
    options.push({ label: '已取消', value: 0 });
  } else if (currentStatus === 2) { // 进行中
    options.push({ label: '已完成', value: 3 });
    options.push({ label: '已取消', value: 0 });
  } else if (currentStatus === 3) { // 已完成
    options.push({ label: '已取消', value: 0 });
  }
  
  return options;
};

// 处理 token 过期的统一方法
const handleTokenExpired = async (error) => {
  if (error.response && error.response.data && error.response.data.msg) {
    const errorMsg = error.response.data.msg;
    if (errorMsg.includes('登录已过期') || errorMsg.includes('无效的token') || errorMsg.includes('认证失败')) {
      ElMessage.error('登录已过期，请重新登录');
      userStore.logout();
      router.push('/login');
      return true;
    }
  }
  return false;
};

// 加载订单列表
const loadOrders = async () => {
  try {
    loading.value = true;
    
    // 构建查询参数 - 使用 myOrders 接口而不是 list 接口
    const params = {
      page: pagination.current,
      pageSize: pagination.pageSize,
      role: filterForm.role, // 这里传递 role 参数
      ...(filterForm.status && { status: filterForm.status }),
      ...(searchKeyword.value && { keyword: searchKeyword.value })
    };

    console.log('查询参数:', params);

    // 使用 myOrders 接口获取当前用户的订单
    const response = await orderApi.myOrders(params);
    
    if (response.code === 0) {
      orders.value = response.data.list;
      pagination.total = response.data.pagination.total;
      console.log('获取订单成功:', orders.value);
    } else {
      ElMessage.error(response.msg || '获取订单列表失败');
      orders.value = [];
    }
  } catch (error) {
    console.error('加载订单列表失败:', error);
    const isTokenExpired = await handleTokenExpired(error);
    if (!isTokenExpired) {
      ElMessage.error('网络错误，请重试');
    }
    orders.value = [];
  } finally {
    loading.value = false;
  }
};

// 搜索处理
const handleSearch = () => {
  pagination.current = 1;
  loadOrders();
};

// 筛选处理
const handleFilter = () => {
  pagination.current = 1;
  loadOrders();
};

// 重置筛选
const handleReset = () => {
  searchKeyword.value = '';
  filterForm.role = 'buyer';
  filterForm.status = '';
  pagination.current = 1;
  loadOrders();
};

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.pageSize = size;
  pagination.current = 1;
  loadOrders();
};

// 当前页改变
const handleCurrentChange = (page) => {
  pagination.current = page;
  loadOrders();
};

// 返回商品页面
const handleBackToGoods = () => {
  router.push('/goods');
};

// 管理我的商品
const handleManageMyGoods = () => {
  router.push('/mygoods');
};

// 查看订单详情
const handleViewDetail = (order) => {
  currentOrder.value = order;
  detailDialogVisible.value = true;
};

// 查看商品详情
const handleViewGoodDetail = (good) => {
  if (!good || !good.item_id) {
    ElMessage.warning('商品信息不完整');
    return;
  }
  router.push(`/goods/${good.item_id}`);
};

// 更新订单状态
const handleUpdateStatus = (order) => {
  currentOrder.value = order;
  statusForm.newStatus = '';
  statusDialogVisible.value = true;
};

// 确认更新状态
const handleConfirmStatusUpdate = async () => {
  if (!currentOrder.value || !statusForm.newStatus) {
    ElMessage.warning('请选择新状态');
    return;
  }

  try {
    statusLoading.value = true;
    const response = await orderApi.updateStatus(currentOrder.value.order_id, {
      status: statusForm.newStatus
    });
    
    if (response.code === 0) {
      ElMessage.success('订单状态更新成功');
      statusDialogVisible.value = false;
      currentOrder.value = null;
      statusForm.newStatus = '';
      loadOrders();
    } else {
      ElMessage.error(response.msg || '更新失败');
    }
  } catch (error) {
    console.error('更新订单状态失败:', error);
    const isTokenExpired = await handleTokenExpired(error);
    if (!isTokenExpired) {
      ElMessage.error('更新失败，请重试');
    }
  } finally {
    statusLoading.value = false;
  }
};

// 删除订单
const handleDeleteOrder = async (order) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个订单吗？此操作不可撤销。',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    const response = await orderApi.delete(order.order_id);
    
    if (response.code === 0) {
      ElMessage.success('订单删除成功');
      loadOrders();
    } else {
      ElMessage.error(response.msg || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除订单失败:', error);
      const isTokenExpired = await handleTokenExpired(error);
      if (!isTokenExpired) {
        ElMessage.error('删除失败，请重试');
      }
    }
  }
};

// 初始化加载
onMounted(() => {
  console.log('订单管理页面已加载');
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录');
    router.push('/login');
    return;
  }
  loadOrders();
});
</script>

<style scoped>
.order-page {
  padding: 24px;
  background: #f0f2f5;
  min-height: 100vh;
}

.search-filter-section {
  margin-bottom: 24px;
}

.filter-container {
  display: flex;
  gap: 16px;
  align-items: center;
  flex-wrap: wrap;
}

.orders-list-section {
  background: #fff;
  border-radius: 8px;
  padding: 24px;
  min-height: 400px;
}

.order-card {
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
  height: 100%;
}

.order-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.order-id {
  font-weight: 600;
  color: #303133;
  font-size: 14px;
}

.order-actions {
  display: flex;
  gap: 4px;
}

.goods-info {
  display: flex;
  gap: 12px;
  margin-bottom: 12px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.goods-info:hover {
  background: #e9ecef;
}

.goods-image {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  overflow: hidden;
  flex-shrink: 0;
}

.goods-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.no-goods-image {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
  color: #999;
}

.goods-details {
  flex: 1;
  min-width: 0;
}

.goods-title {
  margin: 0 0 4px 0;
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.goods-description {
  margin: 0 0 4px 0;
  color: #606266;
  font-size: 12px;
  line-height: 1.4;
}

.goods-price {
  font-size: 16px;
  font-weight: bold;
  color: #ff4d4f;
}

.users-info {
  margin-bottom: 12px;
}

.user-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.user-label {
  font-size: 12px;
  color: #909399;
  width: 60px;
  flex-shrink: 0;
}

.user-detail {
  display: flex;
  align-items: center;
  flex: 1;
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
}

.order-time {
  color: #909399;
  font-size: 12px;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}

.pagination-section {
  display: flex;
  justify-content: center;
  margin-top: 24px;
}

.order-detail .price {
  font-size: 16px;
  color: #ff4d4f;
  font-weight: bold;
}

.goods-images {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.detail-goods-img {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
}

.user-info {
  display: flex;
  align-items: center;
}

.status-update .el-form-item {
  margin-bottom: 16px;
}
</style>